/*
 * Copyright (c) 2007, Tim Stack
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Tim Stack nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY TIM STACK ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TIM STACK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>

#include "reflecxx.h"

#define BUFFER_SIZE_INCREMENT 1024

static int ensure_buffer_avail(struct reflecxx_buffer *rb, size_t size)
{
    size_t newsize;
    char *newbuf;
    int retval;

    assert(rb != NULL);
    
    newsize = rb->rb_max_size + size + BUFFER_SIZE_INCREMENT;
    if (size < (rb->rb_max_size - rb->rb_used)) {
	retval = 1;
    }
    else if (!(rb->rb_flags & RBF_RESIZABLE)) {
	retval = 0;
    }
    else if ((newbuf = reflecxx_realloc(rb->rb_data, newsize)) == NULL) {
	retval = 0;
    }
    else {
	rb->rb_data = newbuf;
	rb->rb_max_size = newsize;
	retval = 1;
    }
    
    return retval;
}

int rbappendf(struct reflecxx_buffer *rb, size_t size,
	      const char *format,
	      ...)
{
    int retval = 0;
    va_list args;

    assert(rb != NULL);
    assert(format != NULL);
    
    va_start(args, format);
    size += 1;
    if (ensure_buffer_avail(rb, size)) {
	int count = vsnprintf(&rb->rb_data[rb->rb_used],
			      rb->rb_max_size - rb->rb_used,
			      format,
			      args);

	assert(count <= (int)size); /* XXX */
	
	rb->rb_used += count;
	retval = 1;
    }
    va_end(args);

    return retval;
}

int reflecxx_pprint(struct reflecxx_buffer *dst,
		    struct reflecxx_full_type *rft,
		    reflecxx_primitive_t rp)
{
    int retval = 0;

    assert(dst != NULL);

    switch (rft->rft_type) {
    case RT_UNKNOWN:
	break;
    case RT_CHAR:
	retval = rbappendf(dst, 16, "%d", rp.rp_char & 0xff);
	break;
    case RT_SHORT:
	retval = rbappendf(dst, 16, "%hd", rp.rp_short);
	break;
    case RT_INT:
	retval = rbappendf(dst, 32, "%d", rp.rp_int);
	break;
    case RT_LONG:
	retval = rbappendf(dst, 32, "%ld", rp.rp_long);
	break;
    case RT_LONG_LONG:
	retval = rbappendf(dst, 128, "%qd", rp.rp_long_long);
	break;
    case RT_UNSIGNED_CHAR:
	retval = rbappendf(dst, 16, "%u", rp.rp_unsigned_char & 0xff);
	break;
    case RT_UNSIGNED_SHORT:
	retval = rbappendf(dst, 16, "%hu", rp.rp_unsigned_short);
	break;
    case RT_UNSIGNED_INT:
	retval = rbappendf(dst, 32, "%u", rp.rp_unsigned_int);
	break;
    case RT_UNSIGNED_LONG:
	retval = rbappendf(dst, 32, "%lu", rp.rp_unsigned_long);
	break;
    case RT_UNSIGNED_LONG_LONG:
	retval = rbappendf(dst, 128, "%qu", rp.rp_unsigned_long_long);
	break;
    case RT_FLOAT:
	retval = rbappendf(dst, 128, "%.06f", rp.rp_float);
	break;
    case RT_DOUBLE:
	retval = rbappendf(dst, 128, "%.06f", rp.rp_double);
	break;
    case RT_BOOL:
	retval = rbappendf(dst, 8, "%s", rp.rp_char ? "true" : "false");
	break;
    case RT_VOID:
	retval = 1;
	break;
    case RT_STRING:
	if (rp.rp_pointer == 0) {
	    retval = rbappendf(dst, 8, "null");
	}
	else {
	    char *val = reflecxx_escape(rp.rp_pointer);

	    if (val != NULL) {
		retval = rbappendf(dst, strlen(val) + 1, "%s", val);
		reflecxx_free(val);
		val = NULL;
	    }
	}
	break;
    case RT_ENUM:
	{
	    struct reflecxx_enum_element *ree;

	    ree = reflecxx_enum_by_value(rft, rp.rp_int);
	    retval = rbappendf(dst, 8 + strlen(ree->ree_name) + 1,
			      "\"%s\"",
			      ree->ree_name);
	}
	break;
    case RT_STRUCT:
	if (rp.rp_pointer != NULL) {
	    struct reflecxx_struct *rs = rft->rft_type_info.st;
	    int lpc;

	    retval = rbappendf(dst, 4, "{");
	    for (lpc = 0; retval && lpc < rs->rs_field_count; lpc++) {
		struct reflecxx_field *rf = &rs->rs_fields[lpc];
		struct reflecxx_pointer *rptr =
		    rf->rf_full_type.rft_type_info.ptr;
		reflecxx_primitive_t subrp;
		const char *comma = "";
		
		if (lpc > 0)
		    comma = ", ";

		if ((retval = rbappendf(dst, 16 + strlen(rf->rf_name) + 1,
				       "%s\"%s\":",
				       comma,
				       rf->rf_name)) != 0) {
		    subrp = reflecxx_field_get(rp.rp_pointer, rf);
		    if (rf->rf_full_type.rft_type == RT_POINTER &&
			rptr->rp_full_type.rft_type == rft->rft_type &&
			rptr->rp_full_type.rft_type_info.ptr ==
			rft->rft_type_info.ptr) {
			/* printf(file, "%p", subrp.rp_pointer); */
		    }
		    else {
			reflecxx_pprint(dst, &rf->rf_full_type, subrp);
		    }
		}
	    }
	    retval = retval && rbappendf(dst, 4, "}");
	}
	break;
    case RT_ARRAY:
	if (rp.rp_pointer != NULL) {
	    struct reflecxx_array *ra = rft->rft_type_info.arr;
	    char *off = rp.rp_pointer;
	    unsigned int lpc;

	    assert(ra->ra_lo <= ra->ra_hi);
	    
	    retval = rbappendf(dst, 4, "[");
	    for (lpc = ra->ra_lo; retval && lpc <= ra->ra_hi; lpc++) {
		if (lpc == 0 || (retval = rbappendf(dst, 4, ", ")) != 0) {
		    reflecxx_primitive_t subrp;
		    
		    subrp = reflecxx_array_get(off, ra, lpc);
		    retval = reflecxx_pprint(dst,
					     &ra->ra_element_type,
					     subrp);
		}
	    }
	    retval = retval && rbappendf(dst, 4, "]");
	}
	break;
    case RT_UNION:
    case RT_FUNCTION:
	rbappendf(dst, 32, "%p", rp.rp_pointer);
	break;
    case RT_POINTER:
	{
	    struct reflecxx_pointer *rptr = rft->rft_type_info.ptr;
	    
	    switch (rptr->rp_full_type.rft_type) {
	    case RT_STRUCT:
	    case RT_UNION:
		reflecxx_pprint(dst, &rptr->rp_full_type, rp);
		break;
	    default:
		rbappendf(dst, 32, "%p", rp.rp_pointer);
		break;
	    }
	}
	break;
    case RT_BIT_FIELD:
	break;
    default:
	assert(0);
	break;
    }
    
    return retval;
}

int reflecxx_vprint(struct reflecxx_buffer *dst,
		    struct reflecxx_full_type *rft,
		    va_list args)
{
    reflecxx_primitive_t rp = { 0 };
    int retval;

    switch (rft->rft_type) {
    case RT_UNKNOWN:
    case RT_VOID:
	break;
    case RT_CHAR:
	rp.rp_char = va_arg(args, int);
	break;
    case RT_INT:
    case RT_ENUM:
	rp.rp_int = va_arg(args, int);
	break;
    case RT_SHORT:
	rp.rp_short = va_arg(args, int);
	break;
    case RT_LONG:
	rp.rp_long = va_arg(args, long);
	break;
    case RT_LONG_LONG:
	rp.rp_long_long = va_arg(args, long long);
	break;
    case RT_UNSIGNED_CHAR:
	rp.rp_unsigned_char = va_arg(args, unsigned int);
	break;
    case RT_UNSIGNED_INT:
	rp.rp_unsigned_int = va_arg(args, unsigned int);
	break;
    case RT_UNSIGNED_SHORT:
	rp.rp_unsigned_short = va_arg(args, unsigned int);
	break;
    case RT_UNSIGNED_LONG:
	rp.rp_unsigned_long = va_arg(args, unsigned long);
	break;
    case RT_UNSIGNED_LONG_LONG:
	rp.rp_unsigned_long_long = va_arg(args, unsigned long long);
	break;
    case RT_FLOAT:
	rp.rp_float = va_arg(args, double);
	break;
    case RT_DOUBLE:
	rp.rp_double = va_arg(args, double);
	break;
    case RT_BOOL:
	rp.rp_char = va_arg(args, int);
	break;
    case RT_FUNCTION:
    case RT_STRING:
    case RT_ARRAY:
    case RT_STRUCT:
    case RT_UNION:
    case RT_POINTER:
	rp.rp_pointer = va_arg(args, void *);
	break;
    }
    retval = reflecxx_pprint(dst, rft, rp);
    
    return retval;
}

int reflecxx_print(char *buffer,
		   size_t size,
		   struct reflecxx_full_type *rft,
		   ...)
{
    struct reflecxx_buffer dst = { NULL, 0, 0, 0, 0 };
    va_list args;
    int retval;

    dst.rb_data = buffer;
    dst.rb_max_size = size;

    va_start(args, rft);
    retval = reflecxx_vprint(&dst, rft, args);
    va_end(args);
    
    return retval;
}

char *reflecxx_aprint(struct reflecxx_full_type *rft, ...)
{
    struct reflecxx_buffer dst = { NULL, 0, 0, 0, RBF_RESIZABLE };
    char *retval;
    va_list args;

    va_start(args, rft);
    if (!reflecxx_vprint(&dst, rft, args)) {
	reflecxx_free(dst.rb_data);
	retval = NULL;
    }
    else {
	retval = dst.rb_data;
    }
    va_end(args);

    return retval;
}
